import React, {lazy} from 'react'
import {Divider, Space, Table} from "antd";
import styled from "@emotion/styled";
import {TableProps} from "antd/lib/table/Table";
import {ColumnType} from "rc-table/lib/interface";
import NoBorderButton from "./noBorderButton";
import {operatedType} from "types";
import {isColumnsData} from 'utils/utils'

const Img = lazy(() => import('./img'))

interface columnsTypes {
    dataType?: string, // 'img' | 'slot'
}

type columns = columnsTypes & ColumnType<any>

interface TableType extends Omit<TableProps<any>, 'columns'> {
    columns: columns[],
    operated?: operatedType,
    operations?: boolean,
    fn?: (e: unknown) => string
}

export interface DataType {
    key: React.Key;
    name: string;
    picture: string,
}


export default function TablePage(props: TableType) {
    const {columns, children, operated, operations = true} = props
    columns?.map(column => {
        if (!(column.ellipsis === false)) {
            column.ellipsis = true
        }
        if (column?.dataType === 'img') {
            column.render = (_: any, record: DataType) => {
                return <Img src={record?.picture}/>
            }
        }
        delete column.dataType
        return column
    })

    const isOperation = isColumnsData(columns, 'operation')
    const isInitOperation = isColumnsData(columns, 'initOperation')
    const initOperation = {
        title: '操作',
        dataIndex: 'initOperation',
        width: '150px',
        ellipsis: false,
        render: (_: any, record: DataType) => {
            return (
                <Space>
                    <NoBorderButton iconcolor={'#1890ff'} icon={'tianxie'}
                                    onClick={() => operated?.({type: 'edit', data: record})}>编辑</NoBorderButton>
                    <NoBorderButton iconcolor={'red'} icon={'shanchu'}
                                    onClick={() => operated?.({type: 'delete', data: record})}><span style={{
                        color: 'red'
                    }}>删除</span></NoBorderButton>
                </Space>
            )
        }
    }

    if (!isOperation && isInitOperation && operations) {
        columns.pop()
    }
    if (operations) columns.push(initOperation)
    return (
        <Container>
            {children}
            {children ? <Divider/> : null}
            <Table rowKey={'id'} pagination={{defaultCurrent: 1, total: 20}} {...props} />
        </Container>
    );
};

const Container = styled.div`
  box-shadow: 0 0.14286rem 0.85714rem 0 rgb(0 0 0 / 10%);
  background-color: #fff;
  border-radius: 5px;
  padding: 2rem;
`